import React, { useState, useEffect, useRef } from 'react';
// import { Form, Input, Button, DatePicker, Space  } from 'antd';
// import 'antd/dist/antd.css';
import './App.css';

// 定义示例数据，仅在开发模式下使用
const DEV_EXAMPLE_EVENTS: Event[] = [
  {
    id: 1,
    time: '1998年夏',
    place: '老家三楼的木质书桌前',
    people: '总穿蓝色工装的父亲，说话时习惯用扳手敲桌面',
    reason: '父亲突然失业，家里开始变卖家具',
    actions: '偷拿压岁钱给母亲买了护手霜，却被她严厉训斥',
    emotions: '手在发抖，不敢看父亲的眼睛',
    psychological: '突然明白"诚实"不是对错，而是彼此的信任',
    reflection: '现在才懂，父亲当年的沉默不是冷漠，而是他笨拙的骄傲',
    impact: '我更加珍惜每一份工作机会，也学会了在困境中保持尊严',
    connections: '二十年后我创业失败时，想起了父亲当年的眼神，找到了继续前行的力量',
    symbolism: '那把他常用的扳手，后来成为我工作室的logo设计灵感',
    sensoryDetails: '夏日午后的阳光透过窗户，照在父亲粗糙的手上，有机油和金属的气味'
  },
  {
    id: 2,
    time: '2005年春季',
    place: '县城火车站前的梧桐树下',
    people: '大学同桌阿芳，总是带着红色发卡',
    reason: '第一次离家去外地求学',
    actions: '在车站犹豫了两小时才最终上车',
    emotions: '既兴奋又恐惧，心跳加速',
    psychological: '意识到成长就是不断告别熟悉的事物',
    reflection: '离开舒适区是痛苦的，但也是必要的成长过程',
    impact: '从此更勇于接受新环境和挑战',
    connections: '这段经历让我在十年后敢于出国留学',
    symbolism: '火车站成为我生命中"转变"的象征',
    sensoryDetails: '春风中梧桐树叶的沙沙声，混合着月台上的广播和火车汽笛'
  }
];

// 开发模式下的表单示例数据
const DEV_EXAMPLE_EVENT: Event = {
  id: Date.now(),
  time: '2010年秋',
  place: '大学图书馆的角落',
  people: '戴眼镜的王教授，总是带着一本旧诗集',
  reason: '偶然翻到一本改变我人生的书',
  actions: '连续三天没去上课，只为读完那本书',
  emotions: '激动不已，仿佛找到了人生方向',
  psychological: '第一次感受到知识的力量能如此强大',
  reflection: '选择的重要性有时体现在偶然的机会中',
  impact: '从此确定了我的专业方向和职业道路',
  connections: '五年后我出版的第一本书，就是受那次阅读体验的启发',
  symbolism: '那本书成为我精神成长的里程碑',
  sensoryDetails: '泛黄书页的油墨香和下午四点透过窗户的斜阳，照在布满灰尘的书架上'
};

interface Event {
  id: number;
  // 事件基础坐标
  time: string;
  place: string;
  people: string;
  // 事件核心动因
  reason: string;
  actions: string;
  // 自我视角
  emotions: string;
  psychological: string;
  reflection: string;
  // 延伸价值
  impact: string;
  connections: string;
  symbolism: string;
  // 感官记忆
  sensoryDetails: string;
}

const App: React.FC = () => {
  // 检查当前环境模式
  const isDevelopment = import.meta.env.VITE_APP_MODE === 'development';
  
  // 根据模式设置初始事件和表单数据
  const [events, setEvents] = useState<Event[]>(isDevelopment ? DEV_EXAMPLE_EVENTS : []);
  const [currentEvent, setCurrentEvent] = useState<Event>(isDevelopment ? DEV_EXAMPLE_EVENT : {
    id: Date.now(),
    time: '',
    place: '',
    people: '',
    reason: '',
    actions: '',
    emotions: '',
    psychological: '',
    reflection: '',
    impact: '',
    connections: '',
    symbolism: '',
    sensoryDetails: ''
  });

  const [isEditing, setIsEditing] = useState(false);
  
  // 新增状态用于生成回忆录功能
  const [isGenerating, setIsGenerating] = useState(false);
  const [generatedContent, setGeneratedContent] = useState('');
  const [streamedText, setStreamedText] = useState('');
  const generatedContentRef = useRef<HTMLDivElement>(null);

  // 在开发模式下显示环境标记
  useEffect(() => {
    if (isDevelopment) {
      console.log('应用运行在开发模式下，已预填充示例数据');
    }
  }, [isDevelopment]);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setCurrentEvent({
      ...currentEvent,
      [name]: value
    });
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    if (isEditing) {
      setEvents(events.map(event => 
        event.id === currentEvent.id ? currentEvent : event
      ));
      setIsEditing(false);
    } else {
      setEvents([...events, { ...currentEvent, id: Date.now() }]);
    }
    
    // 重置表单
    setCurrentEvent({
      id: Date.now(),
      time: '',
      place: '',
      people: '',
      reason: '',
      actions: '',
      emotions: '',
      psychological: '',
      reflection: '',
      impact: '',
      connections: '',
      symbolism: '',
      sensoryDetails: ''
    });
  };

  const handleEditEvent = (event: Event) => {
    setCurrentEvent(event);
    setIsEditing(true);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleDeleteEvent = (id: number) => {
    setEvents(events.filter(event => event.id !== id));
  };

  const handleNewEvent = () => {
    setIsEditing(false);
    setCurrentEvent({
      id: Date.now(),
      time: '',
      place: '',
      people: '',
      reason: '',
      actions: '',
      emotions: '',
      psychological: '',
      reflection: '',
      impact: '',
      connections: '',
      symbolism: '',
      sensoryDetails: ''
    });
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  // 修改模拟流式返回文本的函数
  const simulateStreamResponse = async (eventsData: Event[]) => {
    // 这里之后会替换为实际的ChatGPT API调用
    setIsGenerating(true);
    setStreamedText('');
    
    // 简化为生成单个段落而非完整文章
    //@ts-ignore
    let eventsSummary = '';
    
    // 选择重要事件特征
    const timeSpans = eventsData.map(e => e.time).join('、');
    const mainPeople = [...new Set(eventsData.map(e => e.people.split('，')[0]))].slice(0, 3).join('、');
    //@ts-ignore
    const strongEmotions = [...new Set(eventsData.filter(e => e.emotions.length > 5).map(e => e.emotions))].slice(0, 2).join('和');
    
    // 选择一个有反思内容的事件
    const reflectiveEvent = eventsData.find(e => e.reflection && e.reflection.length > 20);
    
    // 生成一段凝练的摘要
    const fullText = `在${timeSpans}的岁月里，${mainPeople}等人在我的生命中留下了深刻的印记。${
      eventsData.length > 0 
        ? `其中最难忘的是在${eventsData[0].place}，${eventsData[0].reason}。当时的我${eventsData[0].actions}，内心充满了${eventsData[0].emotions}。${eventsData[0].sensoryDetails ? eventsData[0].sensoryDetails + '。' : ''}`
        : ''
    }${
      eventsData.length > 1
        ? `还有在${eventsData[1].place}，我和${eventsData[1].people}一起经历了${eventsData[1].reason}。${eventsData[1].emotions ? '那种' + eventsData[1].emotions + '的感觉至今难忘。' : ''}`
        : ''
    }${
      reflectiveEvent
        ? `回首往事，${reflectiveEvent.reflection}。`
        : '这些经历塑造了今天的我，让我更加珍视生命中的每一段旅程。'
    }通过这些经历，我深刻体会到${
      eventsData.find(e => e.impact && e.impact.length > 10)
        ? eventsData.find(e => e.impact && e.impact.length > 10)!.impact
        : '人生的价值在于与他人的真诚连接和自我的不断成长'
    }。`;
    
    // 模拟流式返回
    for (let i = 0; i <= fullText.length; i += 3) {
      await new Promise(resolve => setTimeout(resolve, 20)); // 控制速度
      const chunk = fullText.slice(0, i);
      setStreamedText(chunk);
    }
    
    // 完成生成
    setGeneratedContent(fullText);
    setIsGenerating(false);
    
    // 滚动到生成的内容
    setTimeout(() => {
      if (generatedContentRef.current) {
        generatedContentRef.current.scrollIntoView({ behavior: 'smooth' });
      }
    }, 500);
  };

  // 处理生成回忆录的函数
  const handleGenerateMemoir = () => {
    if (events.length === 0) {
      alert('请至少添加一个生命事件后再生成回忆录');
      return;
    }
    
    simulateStreamResponse(events);
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>自传回忆录</h1>
        <p className="subtitle">记录生命中的重要时刻，编织你的个人历史</p>
        {isDevelopment && <div className="dev-mode-indicator">开发模式</div>}
      </header>

      <div className="content-container">
        <section className="form-section">
          <h2>{isEditing ? '编辑事件' : '记录新事件'}</h2>
          <form onSubmit={handleSubmit}>
            {/* 事件基础坐标 */}
            <div className="form-group coordinates-section">
              <h3>一、事件的基础坐标</h3>
              <div className="form-row">
                <div className="form-field">
                  <label htmlFor="time">时间 <span className="required">*</span></label>
                  <input 
                    type="text" 
                    id="time" 
                    name="time" 
                    value={currentEvent.time}
                    onChange={handleInputChange}
                    placeholder="精确到具体年份/季节，如：1998年夏"
                    required
                  />
                  <small>时间能锚定记忆坐标，也隐含时代背景</small>
                </div>

                <div className="form-field">
                  <label htmlFor="place">地点 <span className="required">*</span></label>
                  <input 
                    type="text" 
                    id="place" 
                    name="place" 
                    value={currentEvent.place}
                    onChange={handleInputChange}
                    placeholder="具体到场景，如：老家三楼的木质书桌"
                    required
                  />
                  <small>空间细节能触发读者的画面感，承载个人情感</small>
                </div>
              </div>

              <div className="form-field">
                <label htmlFor="people">核心人物 <span className="required">*</span></label>
                <textarea 
                  id="people" 
                  name="people" 
                  value={currentEvent.people}
                  onChange={handleInputChange}
                  placeholder="明确事件中的关键角色及特质，如：总穿蓝色工装的父亲，说话时习惯用扳手敲桌面"
                  required
                />
                <small>人物是事件的情感载体，注明与你的关系及特点</small>
              </div>
            </div>

            {/* 事件核心动因 */}
            <div className="form-group motivation-section">
              <h3>二、事件的核心动因</h3>
              <div className="form-field">
                <label htmlFor="reason">触发事件的原因 <span className="required">*</span></label>
                <textarea 
                  id="reason" 
                  name="reason" 
                  value={currentEvent.reason}
                  onChange={handleInputChange}
                  placeholder="外部诱因或内心驱动，如：母亲突然失业，家里开始变卖家具"
                  required
                />
                <small>动因揭示事件的背景逻辑</small>
              </div>

              <div className="form-field">
                <label htmlFor="actions">你的具体行为 <span className="required">*</span></label>
                <textarea 
                  id="actions" 
                  name="actions" 
                  value={currentEvent.actions}
                  onChange={handleInputChange}
                  placeholder="记录关键动作、语言或选择，如：我偷拿压岁钱给母亲买了护手霜，却被她严厉训斥"
                  required
                />
                <small>行为细节体现你的性格、价值观或成长节点</small>
              </div>
            </div>

            {/* 自我视角 */}
            <div className="form-group perspective-section">
              <h3>三、事件中的自我视角</h3>
              <div className="form-field">
                <label htmlFor="emotions">即时情感 <span className="required">*</span></label>
                <textarea 
                  id="emotions" 
                  name="emotions" 
                  value={currentEvent.emotions}
                  onChange={handleInputChange}
                  placeholder="记录当时的情绪，如：收到大学录取信时，手在发抖，不敢看父亲的眼睛"
                  required
                />
                <small>情感的真实性是自传的灵魂</small>
              </div>

              <div className="form-field">
                <label htmlFor="psychological">心理变化</label>
                <textarea 
                  id="psychological" 
                  name="psychological" 
                  value={currentEvent.psychological}
                  onChange={handleInputChange}
                  placeholder="若事件带来认知转变，需点明前后心态的差异"
                />
                <small>记录认知转变的过程</small>
              </div>

              <div className="form-field">
                <label htmlFor="reflection">事后反思</label>
                <textarea 
                  id="reflection" 
                  name="reflection" 
                  value={currentEvent.reflection}
                  onChange={handleInputChange}
                  placeholder="以当下视角回望事件，如：现在才懂，父亲当年的沉默不是冷漠，而是他笨拙的骄傲"
                />
                <small>反思赋予事件超越当时的意义，体现成长的纵深</small>
              </div>
            </div>

            {/* 延伸价值 */}
            <div className="form-group value-section">
              <h3>四、事件的延伸价值</h3>
              <div className="form-field">
                <label htmlFor="impact">后续影响</label>
                <textarea 
                  id="impact" 
                  name="impact" 
                  value={currentEvent.impact}
                  onChange={handleInputChange}
                  placeholder="事件如何改变你的生活，如：那次演讲比赛获奖，让我成为班长，从此更主动争取机会"
                />
                <small>影响链让事件成为人生轨迹的节点</small>
              </div>

              <div className="form-field">
                <label htmlFor="connections">与其他事件的关联</label>
                <textarea 
                  id="connections" 
                  name="connections" 
                  value={currentEvent.connections}
                  onChange={handleInputChange}
                  placeholder="注明该事件是否为后续某件事的伏笔"
                />
                <small>建立纪事线索的连贯性</small>
              </div>

              <div className="form-field">
                <label htmlFor="symbolism">象征意义</label>
                <textarea 
                  id="symbolism" 
                  name="symbolism" 
                  value={currentEvent.symbolism}
                  onChange={handleInputChange}
                  placeholder="挖掘事件的隐喻，赋予琐碎事件更深层的主题性"
                />
                <small>让事件形成"个人命运的因果网络"</small>
              </div>
            </div>

            {/* 感官密码 */}
            <div className="form-group sensory-section">
              <h3>五、增强真实感的"感官密码"</h3>
              <div className="form-field">
                <label htmlFor="sensoryDetails">细节记忆 <span className="required">*</span></label>
                <textarea 
                  id="sensoryDetails" 
                  name="sensoryDetails" 
                  value={currentEvent.sensoryDetails}
                  onChange={handleInputChange}
                  placeholder="记录非关键但独特的感官细节，如：暴雨天转学那天，胶鞋里的泥沙混着雨水的腥气"
                  required
                />
                <small>感官记忆比事件本身更难伪造，能瞬间激活读者的代入感</small>
              </div>
            </div>

            <div className="form-actions">
              <button type="submit" className="btn-primary">
                {isEditing ? '保存修改' : '保存事件'}
              </button>
              {isEditing && (
                <button type="button" className="btn-secondary" onClick={handleNewEvent}>
                  取消编辑
                </button>
              )}
            </div>
          </form>
        </section>

        <section className="events-section">
          <div className="events-header">
            <h2>我的生命事件</h2>
            <div className="events-actions">
              <button className="btn-add" onClick={handleNewEvent}>+ 添加新事件</button>
              <button 
                className="btn-generate" 
                onClick={handleGenerateMemoir}
                disabled={isGenerating || events.length === 0}
              >
                生成故事摘要 {events.length > 0 && <span className="event-count">{events.length}</span>}
              </button>
            </div>
          </div>
          
          {events.length === 0 ? (
            <div className="empty-state">
              <p>还没有记录事件，开始记录你的第一个回忆吧！</p>
            </div>
          ) : (
            <div className="events-list">
              {events.map((event) => (
                <div key={event.id} className="event-card">
                  <div className="event-header">
                    <h3>{event.time} · {event.place}</h3>
                    <div className="event-actions">
                      <button 
                        className="btn-edit" 
                        onClick={() => handleEditEvent(event)}
                        aria-label="编辑"
                      >
                        ✎
                      </button>
                      <button 
                        className="btn-delete" 
                        onClick={() => handleDeleteEvent(event.id)}
                        aria-label="删除"
                      >
                        ×
                      </button>
                    </div>
                  </div>
                  
                  <div className="event-content">
                    <div className="event-section">
                      <h4>核心人物</h4>
                      <p>{event.people}</p>
                    </div>
                    
                    <div className="event-section">
                      <h4>事件原因</h4>
                      <p>{event.reason}</p>
                    </div>
                    
                    <div className="event-section">
                      <h4>我的行为</h4>
                      <p>{event.actions}</p>
                    </div>
                    
                    <div className="event-section">
                      <h4>即时情感</h4>
                      <p>{event.emotions}</p>
                    </div>
                    
                    {event.sensoryDetails && (
                      <div className="event-section">
                        <h4>感官细节</h4>
                        <p>{event.sensoryDetails}</p>
                      </div>
                    )}
                  </div>
                  
                  <button 
                    className="btn-expand"
                    onClick={() => handleEditEvent(event)}
                  >
                    查看完整内容
                  </button>
                </div>
              ))}
            </div>
          )}
          
          {/* 生成中的加载指示器 */}
          {isGenerating && (
            <div className="generating-indicator">
              <div className="loading-spinner"></div>
              <p>正在生成您的自传回忆录，请稍候...</p>
            </div>
          )}
        </section>
      </div>
      
      {/* 生成的回忆录内容展示区域 */}
      {(streamedText || generatedContent) && (
        <section className="memoir-section" ref={generatedContentRef}>
          <div className="memoir-header">
            <h2>我的故事摘要</h2>
            {!isGenerating && generatedContent && (
              <div className="memoir-actions">
                <button 
                  className="btn-copy" 
                  onClick={() => {
                    navigator.clipboard.writeText(generatedContent);
                    alert('内容已复制到剪贴板！');
                  }}
                >
                  复制文本
                </button>
              </div>
            )}
          </div>
          <div className="memoir-content">
            {streamedText}
          </div>
        </section>
      )}
    </div>
  );
};

export default App;    